﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WIKID.Controller;
using WIKID.Model;
using WIKID.Common;

namespace WIKID.View
{
    public partial class CreateAccountView : UserControl
    {
        AccountController accountController;
        
        public CreateAccountView()
        {
            InitializeComponent();
            accountController = new AccountController();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            AccountModel accountModel = new AccountModel();
            string accName = tbxName.Text.Trim();
            string accPic = tbxAccPic.Text.Trim();
            decimal accAge = cbAge.Value;

            if (accName.Equals(string.Empty))
                MessageBox.Show(Constants.BLANK_ACCOUNT_NAME[0],Constants.BLANK_ACCOUNT_NAME[1]);
            else if (accPic.Equals(string.Empty))
                MessageBox.Show(Constants.BLANK_ACCOUNT_PICTURE[0],Constants.BLANK_ACCOUNT_PICTURE[1]);
            else if (lvPassword.SelectedItems.Count == 0)
                MessageBox.Show(Constants.BLANK_PASSWORD_PICTURE[0],Constants.BLANK_PASSWORD_PICTURE[1]);
            else
            {
                if (!Directory.Exists(Constants.ACCOUNT_IMAGES_FOLDER))
                {
                    Directory.CreateDirectory(Constants.ACCOUNT_IMAGES_FOLDER);
                }

                String filePath = Constants.ACCOUNT_IMAGES_FOLDER + tbxName.Text + "_Accounts.jpeg";
                try
                {
                    SaveImageFileStream(tbxAccPic.Text, filePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: \n" + ex.Message);
                }
                accountModel.AccName = accName;
                accountModel.AccPic = filePath;
                accountModel.AccAge = Convert.ToInt32(accAge);
                int passId = lvPassword.SelectedItems[0].ImageIndex + 1;
                accountModel.PassId = passId.ToString();
                if (passId < 10)
                {
                    accountModel.PassPic = Constants.PASSWORD_IMAGES_FOLDER + "0" + (lvPassword.SelectedItems[0].ImageIndex + 1).ToString() + ".png";
                }
                else
                {
                    accountModel.PassPic = Constants.PASSWORD_IMAGES_FOLDER + (lvPassword.SelectedItems[0].ImageIndex + 1).ToString() + ".png";
                }
                
                if (accountController.CreateNewAccount(accountModel))
                {
                    MessageBox.Show(Constants.CREATE_ACCOUNT_SUCCESS[0], Constants.CREATE_ACCOUNT_SUCCESS[1]);
                    tbxName.Text = string.Empty;
                    tbxAccPic.Text = string.Empty;
                    pbxAccPic.Image = null;
                    //pbxPassPic.Image = null;
                }
                else
                {
                    MessageBox.Show(Constants.CREATE_ACCOUNT_FAIL[0],Constants.CREATE_ACCOUNT_FAIL[1]);
                }
            }
        }

        private void btnPicBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = @"Images\AccountImages\";
            tbxAccPic.Text = openFile();
            if (tbxAccPic.Text == "") return;
            Image img = new Bitmap(tbxAccPic.Text);
            pbxAccPic.Image = img;
            pbxAccPic.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        private static Boolean SaveImageFileStream(string oldFilePath, string newFilePath)
        {
            Boolean success = false;
            try
            {
                using (FileStream str = new FileStream(Path.Combine(newFilePath), FileMode.Create))
                {
                    MemoryStream ms = new MemoryStream(File.ReadAllBytes(oldFilePath));
                    byte[] ImageBytes = ms.ToArray();
                    str.Write(ImageBytes, 0, Convert.ToInt32(ImageBytes.Length));
                    ms.Close();
                    success = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not Save file into your Account. Original error: \n" + ex.Message);
            }
            return success;
        }

        private String openFile()
        {
            String filePath = "";
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG";
            // Allow the user to select multiple images. this.openFileDialog1.
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                            filePath = openFileDialog1.FileName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: \n" + ex.Message);
                }
            }
            return filePath;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            frmParent.current.Close();
            if(frmLogin.current!=null)
            {
                frmLogin.current.Show();
            }
        }

        private void CreateAccountView_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                Utils utils = new Utils();
                List<string> lsPassword = new List<string>();
                if(Directory.Exists(Constants.PASSWORD_IMAGES_FOLDER))
                {
                    lsPassword = utils.ListingPNGFiles(Constants.PASSWORD_IMAGES_FOLDER);
                }


                foreach (string passwordFileName in lsPassword)
                {
                    Image imgPassword = Image.FromFile(Constants.PASSWORD_IMAGES_FOLDER + passwordFileName);
                    ilPassword.Images.Add(getThumbnaiImage(ilPassword.ImageSize.Width, imgPassword));
                }

                int i = 0;
                foreach (string passwordFileName in lsPassword)
                {
                    this.lvPassword.Items.Add("Password " + passwordFileName.Substring(0, passwordFileName.Length - 4));
                    this.lvPassword.Items[i].ImageIndex = i;
                    i++;
                }

                //for (int i = 0; i < lsPassword.Count; i++)
                //{
                //    this.lvPassword.Items.Add("Image ");
                //    this.lvPassword.Items[i].ImageIndex = i;
                //}
            }
        }

        /// <summary>
        /// Method to get thumbnail of a image
        /// </summary>
        /// <param name="width"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        private Image getThumbnaiImage(int width, Image img)
        {
            Image thumb = new Bitmap(width, width);
            Image tmp = null;

            if (img.Width < width && img.Height < width)
            {
                using (Graphics g = Graphics.FromImage(thumb))
                {
                    int xoffset = (int)((width - img.Width) / 2);
                    int yoffset = (int)((width - img.Height) / 2);
                    g.DrawImage(img, xoffset, yoffset, img.Width, img.Height);
                }
            }
            else
            {
                Image.GetThumbnailImageAbort myCallback = new
                    Image.GetThumbnailImageAbort(ThumbnailCallback);

                if (img.Width == img.Height)
                {
                    thumb = img.GetThumbnailImage(
                             width, width,
                             myCallback, IntPtr.Zero);
                }
                else
                {
                    int k = 0;
                    int xoffset = 0;
                    int yoffset = 0;

                    if (img.Width < img.Height)
                    {
                        k = (int)(width * img.Width / img.Height);
                        tmp = img.GetThumbnailImage(k, width, myCallback, IntPtr.Zero);
                        xoffset = (int)((width - k) / 2);

                    }

                    if (img.Width > img.Height)
                    {
                        k = (int)(width * img.Height / img.Width);
                        tmp = img.GetThumbnailImage(width, k, myCallback, IntPtr.Zero);
                        yoffset = (int)((width - k) / 2);
                    }

                    using (Graphics g = Graphics.FromImage(thumb))
                    {
                        g.DrawImage(tmp, xoffset, yoffset, tmp.Width, tmp.Height);
                    }
                }
            }

            using (Graphics g = Graphics.FromImage(thumb))
            {
                g.DrawRectangle(Pens.Green, 0, 0, thumb.Width - 1, thumb.Height - 1);
            }

            return thumb;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool ThumbnailCallback()
        {
            return true;
        }

    }
}
